package yxy.game.pm2.command.shop;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.magicshop;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ShopMessage;
import yxy.game.pm2.module.player.FunctionHandle;
import yxy.game.pm2.module.shop.handle.StrategyShopHandle;

import java.util.*;

/** 商店 兵法商店 */
@MessageType(proto = Command.StrategyShop, classtype = ShopMessage.StrategyShopRequest.class)
public class CMD_StrategyShop extends Command<ShopMessage.StrategyShopRequest> {

	@Override
	public void execute(MessageSource messageSource, ShopMessage.StrategyShopRequest request) {
		try {
			String playerCode = messageSource.getTag();

			ShopMessage.StrategyShopResponse.Builder response = ShopMessage.StrategyShopResponse.newBuilder();

			new StrategyShopHandle().packResponse(playerCode, response);

			//根据开服时间和showtime过滤商品是否展示
			response.addAllGoods( new StrategyShopHandle().checkShopItemIsShow(playerCode));

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	//根据开服时间和showtime过滤商品是否展示
	private Collection<ShopMessage.Goods> checkShopItemIsShow(String playerCode) {
		Collection<ShopMessage.Goods> goods = new StrategyShopHandle().goods(playerCode);

		try {
			//商品表信息
			Map<String, magicshop> datas = DataCenter.getAllData(magicshop.class);
			ArrayList<String> idList = new ArrayList<>();
			//个人的商品信息
			//根据区id获取开服信息,计算已开服日期
			Long alreadlyPassTime = FunctionHandle.getAlreadlyPassTime(playerCode);
			//获取不展示的商品id集合
			Set<Map.Entry<String, magicshop>> entries = datas.entrySet();
			for (Map.Entry<String, magicshop> entry : entries) {
				int showtime = entry.getValue().getShowtime();
				//showtime不等于0且  已开服时间大于showtime才展示商品
				if (alreadlyPassTime - showtime < 0 || showtime == -1) {
					idList.add(entry.getKey());
				}
			}

			//移除对应的不展示商品
			Iterator<ShopMessage.Goods> iterator = goods.iterator();
			while (iterator.hasNext()) {
				ShopMessage.Goods good = iterator.next();
				int id = good.getId();
				if(idList.contains(String.valueOf(id))){
					iterator.remove();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return goods;
	}


	private void send(MessageSource messageSource, ShopMessage.StrategyShopResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}